package com.jt;

import com.jt.codec.JT808Decoder;
import com.jt.codec.JT808Encoder;
import com.jt.handler.*;
import com.jt.utils.JT808Const;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author wang xiao
 * date 2023/8/9
 */
@Component
public class TcpServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${netty.read-timeout}")
    private int readTimeOut;


    private AuthMsgHandler authMsgHandler;

    private HeartBeatMsgHandler heartBeatMsgHandler;


    private LocationMsgHandler locationMsgHandler;

    private LogoutMsgHandler logOutMsgHandler;

    private RegisterMsgHandler registerMsgHandler;

    private OtherMsgHandler otherMsgHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(
                new IdleStateHandler(readTimeOut, 0, 0, TimeUnit.MINUTES));
        // jt808协议 包头最大长度16+ 包体最大长度1023+分隔符2+转义字符最大姑且算60 = 1100
        pipeline.addLast(
                new DelimiterBasedFrameDecoder(1100, Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER}),
                        Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER, JT808Const.PKG_DELIMITER})));
        pipeline.addLast(new JT808Decoder());
        pipeline.addLast(new JT808Encoder());
        pipeline.addLast(heartBeatMsgHandler);
        pipeline.addLast(locationMsgHandler);
        pipeline.addLast(authMsgHandler);
        pipeline.addLast(registerMsgHandler);
        pipeline.addLast(otherMsgHandler);
        pipeline.addLast(logOutMsgHandler);
    }


    @Autowired
    public void setAuthMsgHandler(AuthMsgHandler authMsgHandler) {
        this.authMsgHandler = authMsgHandler;
    }

    @Autowired
    public void setHeartBeatMsgHandler(HeartBeatMsgHandler heartBeatMsgHandler) {
        this.heartBeatMsgHandler = heartBeatMsgHandler;
    }

    @Autowired
    public void setLocationMsgHandler(LocationMsgHandler locationMsgHandler) {
        this.locationMsgHandler = locationMsgHandler;
    }

    @Autowired
    public void setLogOutMsgHandler(LogoutMsgHandler logOutMsgHandler) {
        this.logOutMsgHandler = logOutMsgHandler;
    }

    @Autowired
    public void setRegisterMsgHandler(RegisterMsgHandler registerMsgHandler) {
        this.registerMsgHandler = registerMsgHandler;
    }

    @Autowired
    public void setOtherMsgHandler(OtherMsgHandler otherMsgHandler) {
        this.otherMsgHandler = otherMsgHandler;
    }
}
